/********************************************************************************************************************/
/**
 *  @skip   $Id:$
 *  @file   HeadImageLoader.java
 *  @brief  ImageLoader used for user head/show display.
 *  @date   2013/12/10 ND) Chenqsh create.
 *
 *  ALL Rights Reserved, Copyright(C) ND LIMITED 2013
 */
/********************************************************************************************************************/

/** @addtogroup HEAD_IMAGE_LOADER_CORE
 * @{ */
package com.common.allCommon;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.common.android.utils.httpRequest.HttpRequest;
import com.nostra13.universalimageloader.cache.disc.DiscCacheAware;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.product.android.business.config.Configuration;
import com.product.android.commonInterface.BaseCommonStruct;
import com.product.android.commonInterface.CIConst;
import com.product.android.commonInterface.CommonInterfaceManager;
import com.starappallcommon.R;

public class StarAppHeadImageLoader {
	public static final String TAG = StarAppHeadImageLoader.class.getSimpleName();
	private static  Context mContext = null;

	private static final String FACE_DISC_CACHE_DIR = "head";
	private static final String SHOW_DISC_CACHE_DIR = "show";
	public static final byte IMAGE_TYPE_HEAD_40 = 0x01;
	public static final byte IMAGE_TYPE_HEAD_100 = 0x02;
	public static final byte IMAGE_TYPE_HEAD_152 = 0x03;
	public static final byte IMAGE_TYPE_HEAD_640 = 0x04;
	public static final byte IMAGE_TYPE_SHOW_F1 = 0x05;
	public static final byte IMAGE_TYPE_SHOW_F300 = 0x06;
//	public static final byte IMAGE_TYPE_SHOW_F1920 = 0x07;
	public static final String FACE_SIZE_40 = "f40";
	public static final String FACE_SIZE_100 = "f100";
	public static final String FACE_SIZE_152 = "f152";
	public static final String FACE_SIZE_640 = "f640";
//	public static final String SHOW_SIZE_F0 = "f0";
	public static final String SHOW_SIZE_F1 = "f1";  //为了HR识人，还得保留
	public static final String SHOW_SIZE_F300 = "f300";
//	public static final String SHOW_SIZE_F1920 = "f1920";
	
	
	private static final String FACE_URL = "face";
	private static final String FACE_VALIDATE_URL = "face/url";
	private static final String FACE_UPLOAD_URL = "face/upload";
//	private static final String FACE_UPDATE_TIME = "face/update";
	
	private static final String SHOW_UPLOAD_URL = "photowall/upload";

	private static final String SHOW_URL = "show"; //暂时用这个显示旧的形象照
	//photowall这个新接口要等照片墙形象照做定宽，原图比例缩放功能后才支持
	public static final String PHOTOWALL_URL = "photowall";  //校友使用
//	private static final String SHOW_MODI_URL = "show/modi";
	private static final String SHOW_UPDATE_TIME = "show/update";


	public static DisplayImageOptions mFaceDisplayOptions = null;
	private static DisplayImageOptions mRoundedFaceDisplayOptions = null;
	public static DisplayImageOptions mShowDisplayOptions = null;
	private static DisplayImageOptions mAppOptions = null;
	public static ImageLoadingListener mAnimateFirstListener = new AnimateFirstDisplayListener();
	
	
	public static DisplayImageOptions mFaceCircleDisplayOptions = null;//圆角参数
	public static DisplayImageOptions mPspCircleDisplayOptions = null;//公众号圆角参数
	public static DisplayImageOptions mPspDisplayOptions = null;//公众号方形参数
	
	
	private  static  IGetHeadUrl mIGetHeadUrlImp;
	
	private  static  IGetHeadUrl mIGetShowUrlImp; //主工程确定获取形象照url方法
	
	
	/**
	 * 设置头像UIR组合的接口。
	 * @n<b>函数名称</b>     :setmIGetHeadUrlImp
	 * @brief
	 * @see
	 * @since    Ver 1.1
	 * @param  @param mIGetHeadUrlImp
	 * @return void
	 * @<b>作者</b>          :  suchangjun
	 * @<b>创建时间</b>      :  2014-4-2下午8:51:42
	 */
	public static void setmIGetHeadUrlImp(IGetHeadUrl mIGetHeadUrlImp) {
		StarAppHeadImageLoader.mIGetHeadUrlImp = mIGetHeadUrlImp;
	}
	public static void setmIGetShowUrlImp(IGetHeadUrl iGetShowUrlImp) {
		StarAppHeadImageLoader.mIGetShowUrlImp = iGetShowUrlImp;
	}
	
//	private volatile static HeadImageLoader instance;
//	/** Returns singleton class instance */
//	public static HeadImageLoader getInstance() {
//		if (instance == null) {
//			synchronized (HeadImageLoader.class) {
//				if (instance == null) {
//					instance = new HeadImageLoader();
//				}
//			}
//		}
//		return instance;
//	}
	

	protected StarAppHeadImageLoader() {
	}
	public synchronized static void init(Context context) {
		if(mContext == null || mFaceDisplayOptions == null || mShowDisplayOptions == null){
			mContext = context.getApplicationContext();
			DiscCacheAware headdiscCache = new UnlimitedDiscCache(StorageUtils
					.getIndividualCacheDirectory(mContext,
							FACE_DISC_CACHE_DIR));
			mFaceDisplayOptions = new DisplayImageOptions.Builder()
										.showStubImage(Configuration.DEFAULTFACEIMAGE)
										.showImageForEmptyUri(Configuration.DEFAULTFACEIMAGE)
										.showImageOnFail(Configuration.DEFAULTFACEIMAGE)
										.cacheInMemory()
										.cacheOnDisc()
										.discCache(headdiscCache).build();
			
			//圆角处理
			mRoundedFaceDisplayOptions = new DisplayImageOptions.Builder()
										.showStubImage(R.drawable.face_default)
										.showImageForEmptyUri(R.drawable.face_default)
										.showImageOnFail(R.drawable.face_default)
										.cacheInMemory()
										.cacheOnDisc()
										.displayer(new RoundedBitmapDisplayer(20))
										.discCache(headdiscCache).build();
			//形象照不进行内存缓存
			mShowDisplayOptions = new DisplayImageOptions.Builder()
										.showStubImage(R.drawable.default_usershow_head)
										.showImageForEmptyUri(R.drawable.default_usershow_head)
										.showImageOnFail(R.drawable.default_usershow_head)
										.cacheOnDisc()
										.discCache(
												new UnlimitedDiscCache(StorageUtils
														.getIndividualCacheDirectory(mContext,
																SHOW_DISC_CACHE_DIR))).build();
			mAppOptions = new DisplayImageOptions.Builder()
									.showStubImage(R.drawable.app_91pp)
									.showImageForEmptyUri(R.drawable.app_91pp)
									.showImageOnFail(R.drawable.app_91pp)
									.cacheInMemory()
									.cacheOnDisc()
									.discCache(headdiscCache).build();
			
			mFaceCircleDisplayOptions = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.face_default_circle)
					.showImageForEmptyUri(R.drawable.face_default_circle)
					.showImageOnFail(R.drawable.face_default_circle).cacheInMemory()
					.cacheOnDisc().displayer(new CircleBitmapDisplayer())
					.discCache(headdiscCache).build();
			
		  mPspCircleDisplayOptions = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.psp_default_circle)
					.showImageForEmptyUri(R.drawable.psp_default_circle)
					.showImageOnFail(R.drawable.psp_default_circle).cacheInMemory()
					.cacheOnDisc().displayer(new CircleBitmapDisplayer())
					.discCache(headdiscCache).build();
		  mPspDisplayOptions= new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.psp_default_circle)
					.showImageForEmptyUri(R.drawable.psp_default_circle)
					.showImageOnFail(R.drawable.psp_default_circle).cacheInMemory()
					.cacheInMemory()
					.cacheOnDisc()
					.discCache(headdiscCache).build();
		} else{
			Log.w(TAG, "Try to initialize HeadImageLoader which had already been initialized before.");
		}
	}
	/*******************************************************************************************/
	/*!
	 *  @brief  Adds display image task to execution pool. Image will be set to ImageView
	 * 			when it's turn.
	 *  @note   This function treats following :\n
	 *  			- Check system head id is validate.
	 *  			- if system head, setImageResource by resId.
	 *  			- else 
	 *  				 1.Create image url by imageType.
	 *  			     2.Call ImageLoader library to download image and display.
	 *  @param  uri		[in] String 
	 *  @param  sysHeadId		[in] String (if isn't system head,set sysHeadId=-1)
	 *  @param  imageType		[in] byte(if is system head,set imageType=-1)
	 *  @param  imageView		[in] ImageView
	 *  @return none.
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	public static void displayImage(long uid, int sysHeadId, byte imageType,ImageView imageView) {
		String imageUrl = null;
		if(sysHeadId >=1 && sysHeadId <= 25){
			//2-1.获取系统头像resId
//			int[] SYS_FACE_RES_ID = new int[]{
//					R.drawable.face1,R.drawable.face2,R.drawable.face3,R.drawable.face4,
//					R.drawable.face5,R.drawable.face6,R.drawable.face7,R.drawable.face8,
//					R.drawable.face9,R.drawable.face10,R.drawable.face11,R.drawable.face12,
//					R.drawable.face13,R.drawable.face14,R.drawable.face15,R.drawable.face16,
//					R.drawable.face17,R.drawable.face18,R.drawable.face19,R.drawable.face20,
//					R.drawable.face21,R.drawable.face22,R.drawable.face23,R.drawable.face24,
//					R.drawable.face25
//			};
			int resId = getResourceId(mContext, "face" + sysHeadId);
			ImageLoader.getInstance().cancelDisplayTask(imageView);
			imageView.setImageResource(resId);
		}else{
			imageUrl = getHeadImageUriByType(uid, imageType);
			try {
				if (imageType == IMAGE_TYPE_SHOW_F1
						|| imageType == IMAGE_TYPE_SHOW_F300) {// || imageType == IMAGE_TYPE_SHOW_F1920
					ImageLoader.getInstance().displayImage(imageUrl, imageView,
							mShowDisplayOptions, mAnimateFirstListener,getHttpHashMap());
				} else {
					ImageLoader.getInstance().displayImage(imageUrl, imageView,
							mFaceDisplayOptions, mAnimateFirstListener);
				}
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}
		}
	}
	//圆角头像使用
	public static void displayImage(long uid, byte imageType, ImageView imageView,int roundPixels) {
		String imageUrl = null;
		BaseCommonStruct msg = new BaseCommonStruct();
		msg.lPara = uid;
		CommonInterfaceManager.INSTANCE.CommonInterfaceID(
				CIConst.CONTACT_MODELID, CIConst.CONTACT_GET_SYSAVATAR_ID_10002, msg);
		int sysAvatarId = msg.iPara;
		
		if(sysAvatarId >=1 && sysAvatarId <= 25){
			int resId = getResourceId(mContext, "face" + sysAvatarId);
			ImageLoader.getInstance().cancelDisplayTask(imageView);
			imageView.setImageResource(resId);
		}else{
			imageUrl = getHeadImageUriByType(uid, imageType);
			if(roundPixels < 0){
				roundPixels = 0;
			}
			((RoundedBitmapDisplayer)mRoundedFaceDisplayOptions.getDisplayer()).setRoundPixels(roundPixels);

			try {
				ImageLoader.getInstance().displayImage(imageUrl, imageView,
									mRoundedFaceDisplayOptions,mAnimateFirstListener,getHttpHashMap());
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 绘制圆形头像。
	 * @n<b>函数名称</b>     :displayCircleImage
	 * @brief
	 * @see
	 * @since    Ver 1.1
	 * @param  @param uid
	 * @param  @param imageType
	 * @param  @param imageView
	 * @param  @param option 如果是null,使用默认的。
	 * @return void
	 * @<b>作者</b>          :  suchangjun
	 * @<b>创建时间</b>      :  2014-4-3下午2:31:17
	 */
	public static void displayCircleImage(long uid, byte imageType,
			ImageView imageView, DisplayImageOptions option) {
		String imageUrl = null;
		BaseCommonStruct msg = new BaseCommonStruct();
		msg.lPara = uid;
		CommonInterfaceManager.INSTANCE.CommonInterfaceID(
				CIConst.CONTACT_MODELID,
				CIConst.CONTACT_GET_SYSAVATAR_ID_10002, msg);
		int sysAvatarId = msg.iPara;
		if (sysAvatarId >= 1 && sysAvatarId <= 25) {
			int resId = getResourceId(mContext, "face" + sysAvatarId);
//			ImageLoader.getInstance().cancelDisplayTask(imageView);
//			imageView.setImageResource(resId);
			imageUrl="drawable://"+resId;
		} else {
			imageUrl = getHeadImageUriByType(uid, imageType);
		}
		
		try {

			if (option == null) {
				option = mFaceCircleDisplayOptions;
			}
			imageView.setTag(uid);
			ImageLoader.getInstance().displayImage(imageUrl, imageView,
					option, mAnimateFirstListener,getHttpHashMap());
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获得图片的url
	 * 
	 * <br>Created 2014-10-15 下午4:26:58
	 * @param fid 图片id
	 * @param imageType byte
	 * @return
	 * @author       caocr
	 */
	public static String getImageUrl(long fid, byte imageType){
        String imageUrl = null;
        BaseCommonStruct msg = new BaseCommonStruct();
        msg.lPara = fid;
        CommonInterfaceManager.INSTANCE.CommonInterfaceID(
                CIConst.CONTACT_MODELID,
                CIConst.CONTACT_GET_SYSAVATAR_ID_10002, msg);
        int sysAvatarId = msg.iPara;

        if (sysAvatarId >= 1 && sysAvatarId <= 25) {
            int resId = StarAppHeadImageLoader.getResourceId(mContext, "face" + sysAvatarId);
            imageUrl="drawable://"+resId;
        } else {
            imageUrl = getHeadImageUriByType(fid, imageType);
        }
        return imageUrl;
    }
	
	/**
	 * 绘制圆形头像。
	 * @n<b>函数名称</b>     :displayCircleImage
	 * @brief
	 * @see
	 * @since    Ver 1.1
	 * @param  @param uid
	 * @param  @param imageType
	 * @param  @param imageView
	 * @param  isCircle 是否是圆形的。
	 * @return void
	 * @<b>作者</b>          :  zhy
	 * @<b>创建时间</b>      :  2014-4-3下午2:31:17
	 */
	public static void displayPspImage(String imageUrl,
			ImageView imageView, boolean isCircle) {
		try {
			DisplayImageOptions option;
			if (isCircle){
				option = mPspCircleDisplayOptions;				
			}else{
				option = mPspDisplayOptions;
			}
			//FRI 明星APP增加
			ImageLoader.getInstance().displayImage(imageUrl, imageView,
					option, mAnimateFirstListener,getHttpHashMap());
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
	}
		
		/**
		 * 根据uid和type 获取图片的的地址。
		 * @n<b>函数名称</b>     :getHeadImageUriByType
		 * @brief
		 * @see
		 * @since    Ver 1.1
		 * @param  @param uid
		 * @param  @param imageType
		 * @param  @return 
		 * @return String
		 * @<b>作者</b>          :  suchangjun
		 * @<b>创建时间</b>      :  2014-4-1上午9:33:38
		 */
		private static String getHeadImageUriByType(long uid, byte imageType) {
			String imageUrl;
			//2-2.获取自定义头像
			switch(imageType){
				case IMAGE_TYPE_HEAD_40:
					imageUrl = getFaceUrl(uid, FACE_SIZE_40);
					break;
				case IMAGE_TYPE_HEAD_100:
					imageUrl = getFaceUrl(uid, FACE_SIZE_100);
					break;
				case IMAGE_TYPE_HEAD_152:
					imageUrl = getFaceUrl(uid, FACE_SIZE_152);
					break;
				case IMAGE_TYPE_HEAD_640:
					imageUrl = getFaceUrl(uid, FACE_SIZE_640);
					break;
				case IMAGE_TYPE_SHOW_F1:
					imageUrl = getShowUrl(uid, SHOW_SIZE_F1);
					break;
				case IMAGE_TYPE_SHOW_F300:
					imageUrl = getShowUrl(uid, SHOW_SIZE_F300);
					break;
//					case IMAGE_TYPE_SHOW_F1920:
//						imageUrl = getShowUrl(uid, SHOW_SIZE_F1920);
//						break;
				default:
					imageUrl = "";
					Log.w(TAG, "Invalid imageType:"+imageType);
			}
			return imageUrl;
		}
	
	
	
	//圆角图片使用
	public static void displayImage(String imageUrl, ImageView imageView) {
		try {
			
			ImageLoader.getInstance().displayImage(imageUrl, imageView,
					mRoundedFaceDisplayOptions, mAnimateFirstListener);
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
	}
	
    /**
     * 养成圆角图片
     * <br>Created 2014-9-23 下午6:25:11
     * @param imageUrl  图片URL
     * @param imageView 装图片的VIEW
     * @param displayImageOptions 图片参数
     * @author       gpy
    */
    public static void displayImage(String imageUrl, ImageView imageView,DisplayImageOptions displayImageOptions) {
        try {
            
            ImageLoader.getInstance().displayImage(imageUrl, imageView,
                    displayImageOptions, mAnimateFirstListener);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
    }
	/*
	 * Display 100*100 head image.
	 */
	public static void displayImage(long uid, int sysHeadId,ImageView imageView) {
		displayImage(uid, sysHeadId, IMAGE_TYPE_HEAD_100, imageView);
	}
	public static void displayImage(long uid, ImageView imageView, byte imageType) {
		BaseCommonStruct msg = new BaseCommonStruct();
		msg.lPara = uid;
		CommonInterfaceManager.INSTANCE.CommonInterfaceID(
				CIConst.CONTACT_MODELID, CIConst.CONTACT_GET_SYSAVATAR_ID_10002, msg);
		int sysAvatarId = msg.iPara;
		displayImage(uid, sysAvatarId, imageType, imageView);
	}
	public static void displayImage(String url, int sysHeadId, boolean isShow,ImageView imageView) {
		if(sysHeadId >=1 && sysHeadId <= 25){
			//2-1.获取系统头像resId
			int resId = getResourceId(mContext, "face" + sysHeadId);
			ImageLoader.getInstance().cancelDisplayTask(imageView);
			imageView.setImageResource(resId);
		}else{
			//2-2.获取自定义头像
			try{
				if(isShow){
					ImageLoader.getInstance().displayImage(url, imageView,
										mShowDisplayOptions,mAnimateFirstListener);
				}else{
					ImageLoader.getInstance().displayImage(url, imageView,
										mFaceDisplayOptions,mAnimateFirstListener);
				}
			} catch (OutOfMemoryError e) {
				e.printStackTrace();
			}
		}
	}
	public static void displayAppImage(String url,ImageView imageView) {
		try{
			ImageLoader.getInstance().displayImage(url, imageView,
					mAppOptions,mAnimateFirstListener);
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
	}
	@TargetApi(Build.VERSION_CODES.DONUT)
	private static int getResourceId(Context context, String name) {
		ApplicationInfo appInfo = context.getApplicationInfo();
		int resId = context.getResources().getIdentifier(name, "drawable",
				appInfo.packageName);
		return resId;
	}
	
	/*******************************************************************************************/
	/*!
	 *  @brief  Get user face incremental update time(need called by async).
	 *  @note   This function treats following :\n
	 *  			- Get last show update time from database
	 *  			- General valid URL string.
	 *  			- Send http request.
	 *  			- Parse http response.
	 *  			- Update database
	 *  			- Remove memory and disk cache
	 *  @return face increment update time response string.
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	private static final String FIELD_UID= "uid";
	private static final String FIELD_URL = "url";
	private static final String FIELD_UPDATETIME = "updatetime";
	private static final String FIELD_SHOWUPDATETIME = "showupdatetime";
	
	/**
	 * db分库专用，后续increUpdateFace(SQLiteDatabase mDb, String sid, long uid)会废除
	 * <br>Created 2014-5-9 下午4:28:04
	 * @param mDb
	 * @param sid
	 * @author       Administrator
	*/
	public static void increUpdateFace(SQLiteDatabase mDb, String sid) {
		StringBuilder responseSb = new StringBuilder();
		StringBuffer urlStrBuf = new StringBuffer();
		long lastUpdateTm = 0l; //上次更新时间
		int total = 0; //需要更新头像总数
		int offset = 0; //分页获取偏移量

		JSONArray jsonArray = null;
		JSONObject jsonTemp = null;
		long mUid = 0l;
		/*
		 * 0.从数据库获取上次更新时间
		 */
		String querySql = "select max(uu_header.updatetime) from uu_header";
		Cursor cursor = mDb.rawQuery(querySql,null);
		if(cursor != null){
			try{
				if(cursor.getCount()>0 && cursor.moveToFirst()){
					lastUpdateTm = cursor.getLong(0);
				}
			}finally{
				cursor.close();
			}
		}
		do{

			/*
			 * 1.根据uid，拼接出头像增量更新请求Url串
			 */

			urlStrBuf.append(Configuration.getOAPServiceUrl() + SHOW_UPDATE_TIME
					+ "?updatetime=" + lastUpdateTm);
			urlStrBuf.append("&pos=" + offset);
			urlStrBuf.append("&size=" + 200);
			/*
			 * 2.发起http请求
			 */
			HttpRequest.getInstance(mContext).setSid(sid);
			HttpRequest.getInstance(mContext).doGet(urlStrBuf.toString(), responseSb);

			/*
			 * 3.解析http response，获取增量update time response串
			 */
            JSONObject json;

			try {
				json = new JSONObject(responseSb.toString());

				total = JSONObjecthelper.getInt(json, "total");
				jsonArray = JSONObjecthelper.getJSONArray(json, "data");

				if (jsonArray != null) {
					int length = jsonArray.length();
					offset += length;
					for (int i = 0; i < length; i++) {
						/*
						 * 4.更新相应的本地数据库的update time
						 */
						jsonTemp = JSONObjecthelper.getJSONObject(jsonArray, i);
						mUid = JSONObjecthelper.getLong(jsonTemp, "uid");
//						Log.e("xxxx", "increUpdateFace:"+total+" uid:"+mUid);
						cursor = mDb.query("\'" + "uu_header" + "\'", null, "uid" + "= \'" + mUid + "\'", null, null, null, null);
				        try{
							HeaderImage headerImage = createFaceHeaderImage(cursor, mUid, 
									JSONObjecthelper.getLong(jsonTemp, "updatetime"));
							updateHeaderDb(mDb, headerImage);
							/*
							 * 5.清除相应缓存
							 */
							removeFaceCache(mUid);
				        }finally{
							if(cursor != null){
								cursor.close();
							}
				        }
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}while(offset < total);
	}
	
	/**
	 * 分db完成后会删除改处理
	 * <br>Created 2014-5-9 下午4:35:13
	 * @param mDb
	 * @param sid
	 * @param uid
	 * @author       Administrator
	*/
	public static void increUpdateFace(SQLiteDatabase mDb, String sid, long uid) {
		StringBuilder responseSb = new StringBuilder();
		StringBuffer urlStrBuf = new StringBuffer();
		long lastUpdateTm = 0l; //上次更新时间
		int total = 0; //需要更新头像总数
		int offset = 0; //分页获取偏移量

		JSONArray jsonArray = null;
		JSONObject jsonTemp = null;
		long mUid = 0l;
		/*
		 * 0.从数据库获取上次更新时间
		 */
		String querySql = String.format("select max(uu_header.updatetime) from uu_header left join uu_user on uu_header.uid = uu_user.fid where uu_user.uid='%s'" 
				,uid);
		Cursor cursor = mDb.rawQuery(querySql,null);
		if(cursor != null){
			try{
				if(cursor.getCount()>0 && cursor.moveToFirst()){
					lastUpdateTm = cursor.getLong(0);
				}
			}finally{
				cursor.close();
			}
		}
		do{

			/*
			 * 1.根据uid，拼接出头像增量更新请求Url串
			 */

			urlStrBuf.append(Configuration.getOAPServiceUrl() + SHOW_UPDATE_TIME
					+ "?updatetime=" + lastUpdateTm);
			urlStrBuf.append("&pos=" + offset);
			urlStrBuf.append("&size=" + 200);
			/*
			 * 2.发起http请求
			 */
			HttpRequest.getInstance(mContext).setSid(sid);
			HttpRequest.getInstance(mContext).doGet(urlStrBuf.toString(), responseSb);

			/*
			 * 3.解析http response，获取增量update time response串
			 */
            JSONObject json;

			try {
				json = new JSONObject(responseSb.toString());

				total = JSONObjecthelper.getInt(json, "total");
				jsonArray = JSONObjecthelper.getJSONArray(json, "data");

				if (jsonArray != null) {
					int length = jsonArray.length();
					offset += length;
					for (int i = 0; i < length; i++) {
						/*
						 * 4.更新相应的本地数据库的update time
						 */
						jsonTemp = JSONObjecthelper.getJSONObject(jsonArray, i);
						mUid = JSONObjecthelper.getLong(jsonTemp, "uid");
//						Log.e("xxxx", "increUpdateFace:"+total+" uid:"+mUid);
						cursor = mDb.query("\'" + "uu_header" + "\'", null, "uid" + "= \'" + mUid + "\'", null, null, null, null);
				        try{
							HeaderImage headerImage = createFaceHeaderImage(cursor, mUid, 
									JSONObjecthelper.getLong(jsonTemp, "updatetime"));
							updateHeaderDb(mDb, headerImage);
							/*
							 * 5.清除相应缓存
							 */
							removeFaceCache(mUid);
				        }finally{
							if(cursor != null){
								cursor.close();
							}
				        }
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}while(offset < total);
		
	}

	/*******************************************************************************************/
	/*!
	 *  @brief  increment update show(need called by async).
	 *  @note   This function treats following :\n
	 *  			- Get last show update time from database
	 *  			- General valid URL string.
	 *  			- Send http request.
	 *  			- Parse http response.
	 *  			- Update database
	 *  			- Remove memory and disk cache
	 *  @return none.
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	/**
	 * db分库专用，后续increUpdateShow(SQLiteDatabase mDb, String sid, long uid)会废除
	 * <br>Created 2014-5-9 下午4:28:04
	 * @param mDb
	 * @param sid
	 * @author       Administrator
	*/
	public static void increUpdateShow(SQLiteDatabase mDb, String sid) {
		StringBuilder responseSb = new StringBuilder();
		StringBuffer urlStrBuf = new StringBuffer();
		long lastUpdateTm = 0l; //上次更新时间
		int total = 0; //需要更新形象照总数
		int offset = 0; //分页获取偏移量

		JSONArray jsonArray = null;
		JSONObject jsonTemp = null;
		long mUid = 0l;
		/*
		 * 0.从数据库获取上次更新时间
		 */
		String querySql = "select max(uu_header.showupdatetime) from uu_header";
		Cursor cursor = mDb.rawQuery(querySql,null);
		if(cursor != null ){
			try{
				if(cursor.getCount()>0 && cursor.moveToFirst()){
					lastUpdateTm = cursor.getLong(0);
				}
			}finally{
				cursor.close();
			}
		}
		do{
			/*
			 * 1.根据uid，拼接出头像增量更新请求Url串
			 */

			urlStrBuf.append(Configuration.getOAPServiceUrl() + SHOW_UPDATE_TIME
					+ "?updatetime1=" + lastUpdateTm);
			urlStrBuf.append("&pos=" + offset);
			urlStrBuf.append("&size=" + 200);
			/*
			 * 2.发起http请求
			 */
			HttpRequest.getInstance(mContext).setSid(sid);
			HttpRequest.getInstance(mContext).doGet(urlStrBuf.toString(), responseSb);

			/*
			 * 3.解析http response，获取增量update time response串
			 */
            JSONObject json;

			try {
				json = new JSONObject(responseSb.toString());

				total = JSONObjecthelper.getInt(json, "total");
				jsonArray = JSONObjecthelper.getJSONArray(json, "data");

				if (jsonArray != null) {
					int length = jsonArray.length();
					offset += length;
					for (int i = 0; i < length; i++) {
						/*
						 * 4.更新相应的本地数据库的update time
						 */
						jsonTemp = JSONObjecthelper.getJSONObject(jsonArray, i);
						mUid = JSONObjecthelper.getLong(jsonTemp, "uid");
						cursor = mDb.query("\'" + "uu_header" + "\'", null, "uid" + "= \'" + mUid + "\'", null, null, null, null);

//						Log.e("xxxx", "increUpdateShow:"+total+" uid:"+mUid);
						try{
							HeaderImage headerImage = createShowHeaderImage(cursor, mUid, 
									JSONObjecthelper.getLong(jsonTemp, "updatetime1"));

							updateHeaderDb(mDb, headerImage);

							/*
							 * 5.清除相应缓存
							 */
							removeShowCache(mUid);
						}finally{
							if(cursor != null){
								cursor.close();
							}
						}
						
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}while(offset < total);
	}
	
	/**
	 * 分db完成后会删除改处理
	 * <br>Created 2014-5-9 下午4:35:13
	 * @param mDb
	 * @param sid
	 * @param uid
	 * @author       Administrator
	*/
	public static void increUpdateShow(SQLiteDatabase mDb, String sid, long uid) {
		StringBuilder responseSb = new StringBuilder();
		StringBuffer urlStrBuf = new StringBuffer();
		long lastUpdateTm = 0l; //上次更新时间
		int total = 0; //需要更新形象照总数
		int offset = 0; //分页获取偏移量

		JSONArray jsonArray = null;
		JSONObject jsonTemp = null;
		long mUid = 0l;
		/*
		 * 0.从数据库获取上次更新时间
		 */
		String querySql = String.format("select max(uu_header.showupdatetime) from uu_header left join uu_user on uu_header.uid = uu_user.fid where uu_user.uid='%s'" 
				,uid);
		Cursor cursor = mDb.rawQuery(querySql,null);
		if(cursor != null ){
			try{
				if(cursor.getCount()>0 && cursor.moveToFirst()){
					lastUpdateTm = cursor.getLong(0);
				}
			}finally{
				cursor.close();
			}
		}
		do{
			/*
			 * 1.根据uid，拼接出头像增量更新请求Url串
			 */

			urlStrBuf.append(Configuration.getOAPServiceUrl() + SHOW_UPDATE_TIME
					+ "?updatetime1=" + lastUpdateTm);
			urlStrBuf.append("&pos=" + offset);
			urlStrBuf.append("&size=" + 200);
			/*
			 * 2.发起http请求
			 */
			HttpRequest.getInstance(mContext).setSid(sid);
			HttpRequest.getInstance(mContext).doGet(urlStrBuf.toString(), responseSb);

			/*
			 * 3.解析http response，获取增量update time response串
			 */
            JSONObject json;

			try {
				json = new JSONObject(responseSb.toString());

				total = JSONObjecthelper.getInt(json, "total");
				jsonArray = JSONObjecthelper.getJSONArray(json, "data");

				if (jsonArray != null) {
					int length = jsonArray.length();
					offset += length;
					for (int i = 0; i < length; i++) {
						/*
						 * 4.更新相应的本地数据库的update time
						 */
						jsonTemp = JSONObjecthelper.getJSONObject(jsonArray, i);
						mUid = JSONObjecthelper.getLong(jsonTemp, "uid");
						cursor = mDb.query("\'" + "uu_header" + "\'", null, "uid" + "= \'" + mUid + "\'", null, null, null, null);

//						Log.e("xxxx", "increUpdateShow:"+total+" uid:"+mUid);
						try{
							HeaderImage headerImage = createShowHeaderImage(cursor, mUid, 
									JSONObjecthelper.getLong(jsonTemp, "updatetime1"));

							updateHeaderDb(mDb, headerImage);

							/*
							 * 5.清除相应缓存
							 */
							removeShowCache(mUid);
						}finally{
							if(cursor != null){
								cursor.close();
							}
						}
						
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}while(offset < total);
	}

	/*******************************************************************************************/
	/*!
	 *  @brief  Send face image modify request.(need called by async).
	 *  @note   This function treats following :\n
	 *  			- Encode big face bitmap to base64 string.
	 *  			- Encode small face bitmap to base64 string.
	 *  			- Send face image modify http request.
	 *  			- Check response code
	 *  				if OK ,then set result =true,and remove cache.
	 *  			- Return result.
	 *  @param  uid		[in] uid
	 *  @param  bigFaceBitmap		[in] Bitmap
	 *  @param  smallFaceBitmap		[in] Bitmap
	 *  @return true(success)/false(fail)
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	public static boolean sendFaceImageUpload(String sid, long uid,
			Bitmap faceBitmap) {
		String requestUrl = "";
		boolean result = false;
		int retCode = 0;
		if (faceBitmap == null) {
			return false;
		}

		// 发送
		// 拼接请求url
		requestUrl = Configuration.getOAPServiceUrl() + FACE_UPLOAD_URL;
		HttpRequest.getInstance(mContext).setSid(sid);
		retCode = HttpRequest.getInstance(mContext).doUploadImage(requestUrl,
				faceBitmap, HttpPost.METHOD_NAME);

		/*
		 * 4.根据response，设置result值
		 */
		if (retCode == HttpStatus.SC_OK || retCode == HttpStatus.SC_CREATED) {
			result = true;
		}
		/*
		 * 5.如果发送成功，则删除本地缓存
		 */
		if (result == true) {
			// 删除本地缓存
			removeFaceCache(uid);
		}
		return result;
	}
	
	/*******************************************************************************************/
	/*!
	 *  @brief  Send show image modify request.(need called by async).
	 *  @note   This function treats following :\n
	 *  			- Encode small face bitmap to base64 string.
	 *  			- Encode big face bitmap to base64 string.
	 *  			- Send face image modify http request.
	 *  			- Check response code
	 *  				if OK ,then set result =true,and remove cache.
	 *  			- Return result.
	 *  @param  uid		[in] uid
	 *  @param  bigFaceBitmap		[in] Bitmap
	 *  @param  smallFaceBitmap		[in] Bitmap
	 *  @return true(success)/false(fail)
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	public static boolean sendShowImageUpload(String sid, long uid, Bitmap showBitmap) {
		String requestUrl = "";
		boolean result = false;
		int retCode = 0;
		if (showBitmap == null) {
			return false;
		}
		/*
		 * 3.发送http请求
		 */

		// 发送
		// 拼接请求url
		requestUrl = Configuration.getOAPServiceUrl() + SHOW_UPLOAD_URL;

		HttpRequest.getInstance(mContext).setSid(sid);
		retCode = HttpRequest.getInstance(mContext).doUploadImage(requestUrl,
				showBitmap, HttpPost.METHOD_NAME);
		/*
		 * 4.根据response，设置result值
		 */
		if (retCode == HttpStatus.SC_OK || retCode == HttpStatus.SC_CREATED) {
			result = true;
		}

		/*
		 * 5.如果发送成功，则删除本地缓存
		 */
		if (result == true) {
			// 删除本地缓存
			removeShowCache(uid);
		}
		return result;
	}
	
	/*******************************************************************************************/
	/*!
	 *  @brief  Check if face image is up-to-date.(need called by async).
	 *  @note   This function treats following :\n
	 *  			- get update time from server
	 *  			- get update time from db.
	 *  			- Judge update time
	 *  				if not equal,then update database and remove cache.
	 *  @param  uid		[in] long
	 *  @return true(up-to-date)/false(out-of-date)
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	public static void updateFaceIfOutOfDate(SQLiteDatabase mDb, long uid){
		long updateTimeFromServer = 0l;
		long updateTimeFromClient = 0l;
		//从服务器获取头像更新时间
		updateTimeFromServer = getFaceUpdateTimeFromServer(uid);
		//从本地数据库获取头像更新时间
		Cursor cursor = mDb.query("\'" + "uu_header" + "\'", null, "uid" + "= \'" + uid + "\'", null, null, null, null);
		try{
			if (cursor != null && cursor.moveToFirst()) {
				updateTimeFromClient = cursor.getLong(cursor
						.getColumnIndex(FIELD_UPDATETIME));
			}
			
			if(updateTimeFromServer != updateTimeFromClient){
				//把updateTimeFromServer更新到本地数据库
				HeaderImage headerImage = createFaceHeaderImage(cursor, uid, 
						updateTimeFromServer);

				updateHeaderDb(mDb, headerImage);
				//清除缓存
				removeFaceCache(uid);
			}
		}finally{
			if(cursor != null){
				cursor.close();
			}
		}
	}
	
	/*******************************************************************************************/
	/*!
	 *  @brief  Check if show image is up-to-date.(need called by async).
	 *  @note   This function treats following :\n
	 *  			- get update time from server
	 *  			- get update time from db.
	 *  			- Judge update time
	 *  				if not equal,then update database and remove cache.
	 *  @param  uid		[in] long
	 *  @return true(up-to-date)/false(out-of-date)
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	public static void updateShowIfOutOfDate(SQLiteDatabase mDb, long uid){
		long updateTimeFromServer = 0l;
		long updateTimeFromClient = 0l;
		//从服务器获取头像更新时间
		updateTimeFromServer = getShowUpdateTimeFromServer(uid);
		//从本地数据库获取头像更新时间
		Cursor cursor = mDb.query("\'" + "uu_header" + "\'", null, "uid" + "= \'" + uid + "\'", null, null, null, null);
		try{
			if (cursor != null && cursor.moveToFirst()) {
				updateTimeFromClient = cursor.getLong(cursor
						.getColumnIndex(FIELD_SHOWUPDATETIME));
			}
			
			if(updateTimeFromServer != updateTimeFromClient){
				//把updateTimeFromServer更新到本地数据库
				HeaderImage headerImage = createShowHeaderImage(cursor, uid, 
						updateTimeFromServer);

				updateHeaderDb(mDb, headerImage);
				//清除缓存
				removeFaceCache(uid);
			}
		}finally{
			if(cursor != null){
				cursor.close();
			}
		}
	}

	/**
	 * 根据ImageView的宽度去调整高度,排行榜专用
	 * 
	 * @param uid
	 * @param image
	 * @param type
	 *            参见@ImageType
	 */

	public enum ImageType {
		LARGE, MIDIUM, DEFAULT
	}

	public static void displayRankImage(int screenWidth, long uid,
			int sysHeadId, ImageView imageView, ImageType type) {
		int width = 0;
		int height = 0;
		ViewGroup.LayoutParams params = imageView.getLayoutParams();
		if (params == null) {
			params = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
		}
		if (type == ImageType.LARGE) {
			// 大图 21:13
			width = screenWidth;
			height = (width * 13) / 21;
			imageView.setScaleType(ScaleType.MATRIX);
		} else if (type == ImageType.MIDIUM) {
			// 小图25:18
			width = screenWidth / 2;
			height = (width * 18) / 25;
			imageView.setScaleType(ScaleType.MATRIX);
		} else {
			height = width = screenWidth / 3;
			imageView.setScaleType(ScaleType.FIT_XY);
		}
		params.width = width;
		params.height = height;
		imageView.setLayoutParams(params);
		// 前3名都取形象照
		if (type == ImageType.LARGE || type == ImageType.MIDIUM) {
			displayImage(uid, -1, IMAGE_TYPE_HEAD_640, imageView);
		} else {
			displayImage(uid, sysHeadId, IMAGE_TYPE_HEAD_152, imageView);
		}
	}
	/*******************************************************************************************/
	/*!
	 *  @brief  Get user face URL String.
	 *  @note   This function treats following :\n
	 *  			- Check size string,if size is null/"" ,then size = FACE_SIZE_100
	 *  			- General valid URL string through uid ,size and other needed strings
	 *  @param  uid		[in] long
	 *  @param  size	[in] String(FACE_SIZE_100,FACE_SIZE_200,FACE_SIZE_640)
	 *  @return face url string.
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	public static String getFaceUrl(long uid, String size) {
		
		if(mIGetHeadUrlImp!=null)
		{
			return mIGetHeadUrlImp.getFaceUrl(uid, size);
		}
		
		StringBuffer urlStrBuf = new StringBuffer();
		if(TextUtils.isEmpty(size)){
			size = FACE_SIZE_100;
		}
		/*
		 * 根据uid和size，拼接出有效的Url串
		 */
		urlStrBuf.append(Configuration.getOAPServiceUrl());
		urlStrBuf.append(FACE_URL);
		urlStrBuf.append("?uid=" + uid);
		urlStrBuf.append("&size=" + size);
		return urlStrBuf.toString();
	}	
	/*******************************************************************************************/
	/*!
	 *  @brief  Get user face URL String exclude size,
	 *  			used to remove all size face caches in memory.
	 *  @note   This function treats following :\n
	 *  			- General URL string exclude size info。
	 *  @param  uid		[in] long
	 *  @return face url string exclude size info.
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	private static String getFaceUrlExcludeSize(long uid) {
		StringBuffer urlStrBuf = new StringBuffer();
		/*
		 * 获取该uid不包含尺寸的url，用于从缓存中删除所有尺寸的头像
		 */
		urlStrBuf.append(Configuration.getOAPServiceUrl());
		urlStrBuf.append(FACE_URL);
		urlStrBuf.append("?uid=" + uid);
		return urlStrBuf.toString();
	}
	/*******************************************************************************************/
	/*!
	 *  @brief  Get user show URL String.
	 *  @note   This function treats following :\n
	 *  			- Check size string,if size is null/"" ,then size = SHOW_SIZE_F0
	 *  			- General valid URL string through uid ,size and other needed strings
	 *  @param  uid		[in] long
	 *  @param  size	[in] String(SHOW_SIZE_F0(source),SHOW_SIZE_F1(thumb))
	 *  @return show url string.
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	public static String getShowUrl(long uid, String sizeStr) {
		if(mIGetShowUrlImp!=null)
		{
			return mIGetShowUrlImp.getFaceUrl(uid, sizeStr);
		}
		
		StringBuffer urlStrBuf = new StringBuffer();
		if(TextUtils.isEmpty(sizeStr)){
			sizeStr = SHOW_SIZE_F1;
		}
		/*
		 * 根据uid和size，拼接出有效的Url串
		 */
		urlStrBuf.append(Configuration.getOAPServiceUrl());
		urlStrBuf.append(SHOW_URL);
//		if(sizeStr.equals(SHOW_SIZE_F1)){
//			urlStrBuf.append(SHOW_URL);
//		}else{
//			urlStrBuf.append(PHOTOWALL_URL);
//		}
		urlStrBuf.append("?uid=" + uid);
		urlStrBuf.append("&size=" + sizeStr);
		return urlStrBuf.toString();
	}
	/*******************************************************************************************/
	/*!
	 *  @brief  Get user face URL String exclude size,
	 *  			used to remove all size show caches in memory.
	 *  @note   This function treats following :\n
	 *  			- General URL string exclude size info
	 *  @param  uid		[in] long
	 *  @return show url string exclude size info.
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	private static String getShowUrlExcludeSize(long uid) {
		StringBuffer urlStrBuf = new StringBuffer();
		/*
		 * 获取该uid不包含尺寸的url，用于从缓存中删除所有尺寸的形象照
		 */
		urlStrBuf.append(Configuration.getOAPServiceUrl());
		urlStrBuf.append(SHOW_URL);
		urlStrBuf.append("?uid=" + uid);
		return urlStrBuf.toString();
	}	
//	private static String getPhotoWallUrlExcludeSize(long uid) {
//		StringBuffer urlStrBuf = new StringBuffer();
//		/*
//		 * 获取该uid不包含尺寸的url，用于从缓存中删除所有尺寸的形象照
//		 */
//		urlStrBuf.append(Configuration.getOAPServiceUrl());
//		urlStrBuf.append(PHOTOWALL_URL);
//		urlStrBuf.append("?uid=" + uid);
//		return urlStrBuf.toString();
//	}
	/*******************************************************************************************/
	/*!
	 *  @brief  Get user face update time(need called by async).
	 *  @note   This function treats following :\n
	 *  			- General valid URL string.
	 *  			- Send http request.
	 *  			- Parse http response to get face update time.
	 *  			
	 *  @param  uid		[in] long
	 *  @return face update time.
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	private static long getFaceUpdateTimeFromServer(long uid) {
		long updateTime = 0l;
		StringBuffer urlStrBuf = new StringBuffer();
		StringBuilder response = new StringBuilder();
		/*
		 * 1.根据uid，拼接出有效的Url串
		 */
		urlStrBuf.append(Configuration.getOAPServiceUrl());
		urlStrBuf.append(FACE_VALIDATE_URL);
		urlStrBuf.append("?uids=" + uid);
		urlStrBuf.append("&size="+ FACE_SIZE_100);
		/*
		 * 2.发起http请求
		 */
		HttpRequest.getInstance(mContext).doGet(urlStrBuf.toString(), response);
		/*
		 * 3.解析http response，获取update time
		 */
		JSONArray jsonarray = asJSONArray(response.toString());
		if (jsonarray != null) {
			JSONObject json = JSONObjecthelper.getJSONObject(jsonarray, 0);
			updateTime = JSONObjecthelper.getLong(json, "updatetime");
		}
		return updateTime;
	}

	/*******************************************************************************************/
	/*!
	 *  @brief  Get user show update time(need called by async).
	 *  @note   This function treats following :\n
	 *  			- General valid URL string.
	 *  			- Send http request.
	 *  			- Parse http response to get show update time.
	 *  			
	 *  @param  uid		[in] long
	 *  @return show update time.
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	private static long getShowUpdateTimeFromServer(long uid) {
		long updateTime = 0l;
		StringBuffer urlStrBuf = new StringBuffer();
		StringBuilder response = new StringBuilder();
		/*
		 * 1.根据uid，拼接出有效的Url串
		 */
		urlStrBuf.append(Configuration.getOAPServiceUrl());
		urlStrBuf.append(FACE_VALIDATE_URL); //用的也是头像照的地址请求？（TBD）
		urlStrBuf.append("?uids=" + uid);
		urlStrBuf.append("&size="+ FACE_SIZE_100);
		/*
		 * 2.发起http请求
		 */
		HttpRequest.getInstance(mContext).doGet(urlStrBuf.toString(), response);
		/*
		 * 3.解析http response，获取update time
		 */
		JSONArray jsonarray = asJSONArray(response.toString());
		if (jsonarray != null) {
			JSONObject json = JSONObjecthelper.getJSONObject(jsonarray, 0);
			updateTime = JSONObjecthelper.getLong(json, "updatetime1");
		}
		return updateTime;
	}
	
	/*******************************************************************************************/
	/*!
	 *  @brief  Remove all sizes face image cache from disk and memory.
	 *  @note   This function treats following :\n
	 *  			- Remove all sizes face image cache from disk.
	 *  			- Remove all sizes face image cache from memory.
	 *  @param  uid		[in] long
	 *  @return null
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	public static void removeFaceCache(long uid){
		//从sdcard中移除所有尺寸的头像缓存
		ImageLoader.getInstance().removeFromDiscCache(mFaceDisplayOptions,
				getFaceUrl(uid,FACE_SIZE_40));
		ImageLoader.getInstance().removeFromDiscCache(mFaceDisplayOptions,
				getFaceUrl(uid,FACE_SIZE_100));
		ImageLoader.getInstance().removeFromDiscCache(mFaceDisplayOptions,
				getFaceUrl(uid,FACE_SIZE_152));
		ImageLoader.getInstance().removeFromDiscCache(mFaceDisplayOptions,
				getFaceUrl(uid,FACE_SIZE_640));
		//从memory中移除所有尺寸的头像缓存
		ImageLoader.getInstance().removeFromMemCache(getFaceUrlExcludeSize(uid));
	}
	/*******************************************************************************************/
	/*!
	 *  @brief  从磁盘和内存缓存中移除指定url的图片缓存
	 *  @param  url		[in] String
	 *  @return null
	 *  @date   2014/3/15 ND) xx create.
	 */
	/*******************************************************************************************/
	public static void removeFaceCache(String url){
		//从sdcard中移除指定url的头像缓存
		ImageLoader.getInstance().removeFromDiscCache(mAppOptions,url);
		//从memory中移除指定url的头像缓存
		ImageLoader.getInstance().removeFromMemCache(url);
	}
	/*******************************************************************************************/
	/*!
	 *  @brief  Remove all sizes show image cache from disk and memory.
	 *  @note   This function treats following :\n
	 *  			- Remove all sizes show image cache from disk.
	 *  			- Remove all sizes show image cache from memory.
	 *  @param  uid		[in] long
	 *  @param  options		[in] DisplayImageOptions
	 *  @return null
	 *  @date   2013/12/10 ND) Chenqsh create.
	 */
	/*******************************************************************************************/
	public static void removeShowCache(long uid){
		//从sdcard中移除所有尺寸的头像缓存
		ImageLoader.getInstance().removeFromDiscCache(mShowDisplayOptions,
				getShowUrl(uid,SHOW_SIZE_F1));
		ImageLoader.getInstance().removeFromDiscCache(mShowDisplayOptions,
				getShowUrl(uid,SHOW_SIZE_F300));
//		ImageLoader.getInstance().removeFromDiscCache(mShowDisplayOptions,
//				getShowUrl(uid,SHOW_SIZE_F1920));
		//从memory中移除所有尺寸的头像缓存
		ImageLoader.getInstance().removeFromMemCache(getShowUrlExcludeSize(uid));
//		ImageLoader.getInstance().removeFromMemCache(getPhotoWallUrlExcludeSize(uid));
	}
	
	/**
	 * 清空公众号头像的缓存
	 * <br>Created 2014-5-19 下午3:04:48
	 * @param url
	 * @author       cb
	*/
	public static void removePspCache(String url){
		ImageLoader.getInstance().removeFromDiscCache(mPspCircleDisplayOptions,url);
		ImageLoader.getInstance().removeFromDiscCache(mPspDisplayOptions,url);
		ImageLoader.getInstance().removeFromMemCache(url);
	}

	private static void updateHeaderDb(SQLiteDatabase mDb, HeaderImage headerImage) {
		ContentValues replaceValues = new ContentValues();
		replaceValues.put(FIELD_UID, headerImage.getUid());
		replaceValues.put(FIELD_URL, headerImage.getUrl());
		replaceValues.put(FIELD_UPDATETIME,
				headerImage.getUpdatetime());
		replaceValues.put(FIELD_SHOWUPDATETIME,
				headerImage.getShowupdatetime());
		
		mDb.beginTransaction();
		try {
			mDb.replace("uu_header", null, replaceValues);
			mDb.setTransactionSuccessful();
		} finally {
			mDb.endTransaction();
		}
	}
	
	private static HeaderImage createFaceHeaderImage(Cursor cursor, long uid, long updateTime){
		HeaderImage headerImage = new HeaderImage();
		if (cursor != null && cursor.moveToFirst()) {
			headerImage.setUrl(cursor.getString(cursor
					.getColumnIndex(FIELD_URL)));
			headerImage.setShowupdatetime(cursor.getLong(cursor
					.getColumnIndex(FIELD_SHOWUPDATETIME)));
		}else{
			headerImage.setUrl("");
			headerImage.setShowupdatetime(0l);
		}
		headerImage.setUid(uid);
		headerImage.setUpdatetime(updateTime);
		return headerImage;
	}
	
	private static HeaderImage createShowHeaderImage(Cursor cursor, long uid, long updateTime){
		HeaderImage headerImage = new HeaderImage();
		if (cursor != null && cursor.moveToFirst()) {
				headerImage.setUrl(cursor.getString(cursor
						.getColumnIndex(FIELD_URL)));
				headerImage.setUpdatetime(cursor.getLong(cursor
						.getColumnIndex(FIELD_UPDATETIME)));
		}else{
			headerImage.setUrl("");
			headerImage.setUpdatetime(0l);
		}
		headerImage.setUid(uid);
		headerImage.setShowupdatetime(updateTime);
		return headerImage;
	}
	
    private static JSONArray asJSONArray(String resStr){
    	JSONArray jsonArray = null;
    	if(TextUtils.isEmpty(resStr)||"null".equals(resStr)){
    		return null;
    	}
        try {
        	jsonArray = new JSONArray(resStr);
        } 
        catch(RuntimeException e){
        	e.printStackTrace();
        }
        catch (Exception e) {
        	e.printStackTrace();
        }
        return jsonArray;
    }
    
	private static class AnimateFirstDisplayListener extends
			SimpleImageLoadingListener {
		
		final List<String> displayedImages = Collections
				.synchronizedList(new LinkedList<String>());
		
		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}
	
	public static class HeaderImage {

		private long uid;
		private String url;
		private long updatetime;
		private long showupdatetime;
		
		public long getUid() {
			return uid;
		}
		public String getUrl() {
			return url;
		}
		public void setUid(long uid) {
			this.uid = uid;
		}
		public void setUrl(String url) {
			this.url = url;
		}
		public long getUpdatetime() {
			return updatetime;
		}
		public void setUpdatetime(long updatetime) {
			this.updatetime = updatetime;
		}
		public long getShowupdatetime() {
			return showupdatetime;
		}
		public void setShowupdatetime(long showupdatetime) {
			this.showupdatetime = showupdatetime;
		}
	}
	
	/**
     * 通过fileId显示圆形头像。uid作为ImageView的tag
     * @n<b>函数名称</b>     :displayCircleImage
     * @brief
     * @see
     * @since    Ver 1.1
     * @param  fileId 文件id
     * @param  uid,用于标识可能需要更新头像显示的ImageView对象,当fileId不合法时生效用于显示头像
     * @param  @param imageType 图片大小类型
     * @param  @param imageView 图片显示组件
     * @param  @param option 如果是null,使用默认的。
     * @return void
     * @<b>作者</b>          :  ChuXY
     * @<b>创建时间</b>      :  2014-4-3下午2:31:17
     */
	public static void displayCircleImageByFileId(long fileId, long uid,
			byte imageType, ImageView imageView, DisplayImageOptions option) {
		if(imageView==null){
			return ;
		}
		imageView.setTag(uid);
		displayCircleImageByFileId(fileId, imageType, imageView, option);
	}
    
	/**
     * 通过fileId显示圆形头像。
     * @n<b>函数名称</b>     :displayCircleImage
     * @brief
     * @see
     * @since    Ver 1.1
     * @param  fileId 文件id
     * @param  @param imageType 图片大小类型
     * @param  @param imageView 图片显示组件
     * @param  @param option 如果是null,使用默认的。
     * @return void
     * @<b>作者</b>          :  ChuXY
     * @<b>创建时间</b>      :  2014-4-3下午2:31:17
     */
	public static void displayCircleImageByFileId(long fileId, byte imageType,
			ImageView imageView, DisplayImageOptions option) {
		if (imageView == null) {
			return;
		}
		String imageUrl = getHeadImageUrlByFileIdAndType(fileId, imageType);
		try {
			if (option == null) {
				option = mFaceCircleDisplayOptions;
			}
			ImageLoader.getInstance().displayImage(imageUrl, imageView, option,
					mAnimateFirstListener, getHttpHashMap());
		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		}
	}
    /**
     * 使用uid获取fileId显示用户头像
     * 
     * <br>Created 2014-10-31 下午3:08:09
     * @param uid 用户id
     * @param 上下文
     * @param imageType 图片类型
     * @param imageView 组件
     * @param option 选项
     * @param modelId 接收线程返回结果的模块id，不需要接收消息则入参-1
     * @param modelId 操作类型
     * @author        ChuXY
     */
	public static void displayCircleImageByUid(Context context, long uid,
			byte imageType, ImageView imageView, DisplayImageOptions option,
			int modelId, int handleType) {
		if (imageView == null || context == null) {
			return;
		}
		long fileId = -1;
		if (uid > 0) {
			BaseCommonStruct struct = new BaseCommonStruct();
			struct.lPara = uid;
			struct.obj1 = context;
			int[] receiver = new int[] { modelId, handleType };
			struct.obj2 = receiver;
			if (CommonInterfaceManager.INSTANCE.CommonInterfaceID(
					CIConst.MAIN_MODELID,
					CIConst.CONTACT_GET_USER_FROMSERVER_10017, struct) == CIConst.COM_RET_OK) {
				fileId =  struct.lPara;
			}
		}
		displayCircleImageByFileId(fileId,uid ,imageType, imageView, option);
	}

    /**
     * 根据fileId和type 获取图片的的地址。
     * @n<b>函数名称</b>     :getHeadImageUriByType
     * @brief
     * @see
     * @since    Ver 1.1
     * @param  fileId 文件id
     * @param  imageType 图片大小类型
     * @return String 根据fileId和type 获取图片的的地址
     * @<b>作者</b>          :  ChuXY
     * @<b>创建时间</b>      :  2014-4-1上午9:33:38
     */
    public static String getHeadImageUrlByFileIdAndType(long fileId, byte imageType) {
        String imageUrl;
        //2-2.获取自定义头像
        switch(imageType){
            case IMAGE_TYPE_HEAD_40:
                imageUrl = getFaceUrlByFileId(fileId, FACE_SIZE_40);
                break;
            case IMAGE_TYPE_HEAD_100:
                imageUrl = getFaceUrlByFileId(fileId, FACE_SIZE_100);
                break;
            case IMAGE_TYPE_HEAD_152:
                imageUrl = getFaceUrlByFileId(fileId, FACE_SIZE_152);
                break;
            case IMAGE_TYPE_HEAD_640:
                imageUrl = getFaceUrlByFileId(fileId, FACE_SIZE_640);
                break;
            default:
                imageUrl = "";
                Log.w(TAG, "Invalid imageType:"+imageType);
        }
        return imageUrl;
    }
    
    /**
     * 根据fileId获取显示头像的路径
     * 
     * <br>Created 2014-10-22 下午2:56:37
     * @param fileId 文件id
     * @param sizeStr 图片大小
     * @return 显示路径
     * @author        ChuXY
     */
    private static String getFaceUrlByFileId(long fileId, String sizeStr) {
        if (mIGetHeadUrlImp != null) {
            return mIGetHeadUrlImp.getFaceUrlByFileId(fileId, sizeStr);
        }
        return null;
    }
    
	/**
	 * 获取头部HashMap
	 * 
	 * <br>Created 2014-9-9 下午7:32:51
	 * @return 头部HashMap
	 * @author        ChuXY
	 */
    public static HashMap<String, String> getHttpHashMap() {
        //FRI scj allcommon 重构优化。
        if (mIGetHeadUrlImp == null) {
            return null;
        } else {
            return mIGetHeadUrlImp.getHttpHashMap();
        }
    }
	
	
}
/* @} */